<template>
  <div class="event-detail-container">
    <div class="page-header">
      <h2>活动详情</h2>
      <div class="header-actions">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <el-button 
          v-if="userRole === 'admin'" 
          type="primary" 
          @click="editEvent" 
          icon="Edit">
          编辑活动
        </el-button>
      </div>
    </div>

    <div v-loading="loading" class="event-detail-card">
      <div v-if="eventDetail" class="detail-content">
        <div class="detail-header">
          <h1 class="event-title">{{ eventDetail.title }}</h1>
          <div class="header-right">
            <el-tag class="status-tag" :type="getStatusType(eventDetail.status)">
              {{ getStatusText(eventDetail.status) }}
            </el-tag>
          </div>
        </div>
        
        <el-divider />
        
        <!-- 活动封面 -->
        <div v-if="eventDetail.cover" class="cover-section">
          <el-image
            :src="getImageUrl(eventDetail.cover)"
            fit="contain"
            class="event-cover"
            :preview-src-list="[getImageUrl(eventDetail.cover)]"
          >
            <template #error>
              <div class="image-error">
                <el-icon><Picture /></el-icon>
                <span>图片加载失败</span>
                <el-button type="primary" size="small" @click="reloadImage" style="margin-top: 10px;">
                  重新加载
                </el-button>
              </div>
            </template>
          </el-image>
        </div>
        
        <el-divider v-if="eventDetail.cover" />
        
        <div class="detail-info">
          <div class="info-section">
            <div class="info-item">
              <span class="label">活动地点：</span>
              <span class="value">{{ eventDetail.location }}</span>
            </div>
            <div class="info-item">
              <span class="label">开始时间：</span>
              <span class="value">{{ eventDetail.startTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">结束时间：</span>
              <span class="value">{{ eventDetail.endTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">参与人数：</span>
              <span class="value">{{ eventDetail.participantCount || 0 }} 人</span>
            </div>
            <div class="info-item">
              <span class="label">活动分类：</span>
              <span class="value">{{ eventDetail.category || '未分类' }}</span>
            </div>
            <div class="info-item">
              <span class="label">活动标签：</span>
              <span class="value">{{ eventDetail.tags || '无标签' }}</span>
            </div>
            <div class="info-item">
              <span class="label">浏览量：</span>
              <span class="value">{{ eventDetail.viewCount || 0 }}</span>
            </div>
          </div>
          
          <el-divider />
          
          <div class="description-section">
            <h3>活动描述</h3>
            <div class="event-description">
              {{ eventDetail.description || '暂无描述' }}
            </div>
          </div>
          
          <el-divider v-if="eventDetail.notes" />
          
          <div v-if="eventDetail.notes" class="notes-section">
            <h3>活动须知</h3>
            <div class="event-notes">
              {{ eventDetail.notes }}
            </div>
          </div>
          
          <el-divider v-if="eventDetail.participants && eventDetail.participants.length > 0" />
          
          <div v-if="eventDetail.participants && eventDetail.participants.length > 0" class="participants-section">
            <participant-list :participants="eventDetail.participants" />
          </div>
          
          <el-divider v-if="isOrganizer || userRole === 'admin'" />
          
          <!-- 票种管理组件 -->
          <div v-if="isOrganizer || userRole === 'admin'" class="tickets-section">
            <ticket-management 
              :eventId="eventId" 
              :editable="eventDetail.status !== 'offline'"
              @update="handleTicketUpdate"
            />
          </div>
        </div>
      </div>
      
      <el-empty v-else description="未找到活动信息" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { getEventDetail, joinEvent, cancelJoinEvent } from '@/api/event'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Edit, Picture, Refresh } from '@element-plus/icons-vue'
import ParticipantList from './components/ParticipantList.vue'
import TicketManagement from './components/TicketManagement.vue'
import { getFullImageUrl, addCacheBuster, parseImageData } from '@/utils/imageHelper'

// 路由对象和路由实例
const route = useRoute()
const router = useRouter()
// 用户存储
const userStore = useUserStore()
// 获取用户角色和ID
const userRole = computed(() => userStore.role)
const userId = computed(() => userStore.userId)

// 活动ID
const eventId = computed(() => route.params.id)
// 加载状态
const loading = ref(false)
const actionLoading = ref(false)
// 活动详情数据
const eventDetail = ref(null)
// 当前用户是否已参与
const isJoined = computed(() => {
  if (!eventDetail.value || !eventDetail.value.participants) return false
  return eventDetail.value.participants.some(p => p.id === userId.value)
})
// 图片URL缓存破坏版本
const imageVersion = ref(Date.now())
// 当前用户是否是组织者
const isOrganizer = computed(() => {
  if (!eventDetail.value) return false
  return eventDetail.value.creatorId === userId.value
})

// 页面加载时获取活动详情
onMounted(() => {
  if (eventId.value) {
    fetchEventDetail()
  } else {
    ElMessage.error('活动ID不能为空')
    goBack()
  }
})

// 获取带有缓存破坏参数的图片URL
const getImageUrl = (url) => {
  if (!url) return '';
  
  // 先解析图片数据，再转为完整URL，最后添加缓存参数
  const parsedUrl = parseImageData(url);
  console.log('原始URL:', url);
  console.log('解析后URL:', parsedUrl);
  
  // 添加缓存参数并返回完整URL
  return addCacheBuster(getFullImageUrl(parsedUrl));
}

// 重新加载图片
const reloadImage = () => {
  imageVersion.value = Date.now()
  // 强制Vue重新渲染组件
  if (eventDetail.value) {
    const tempDetail = { ...eventDetail.value }
    eventDetail.value = null
    setTimeout(() => {
      eventDetail.value = tempDetail
    }, 100)
  }
}

// 获取活动详情
const fetchEventDetail = async () => {
  loading.value = true
  try {
    const res = await getEventDetail(eventId.value)
    if (res.code === 200) {
      eventDetail.value = res.data
      // 更新图片版本号
      imageVersion.value = Date.now()
    } else {
      ElMessage.error(res.msg || '获取活动详情失败')
    }
  } catch (error) {
    console.error('获取活动详情异常:', error)
    ElMessage.error('获取活动详情失败')
  } finally {
    loading.value = false
  }
}

// 获取状态对应的Tag类型
const getStatusType = (status) => {
  switch (status) {
    case 'draft': return 'info'
    case 'online': return 'success'
    case 'offline': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'draft': return '草稿'
    case 'online': return '已上线'
    case 'offline': return '已下线'
    default: return '未知'
  }
}

// 参与活动
const handleJoinEvent = async () => {
  if (eventDetail.value.status !== 'online') {
    ElMessage.warning('只能参与已上线的活动')
    return
  }
  
  try {
    actionLoading.value = true
    const res = await joinEvent(eventId.value)
    if (res.code === 200) {
      ElMessage.success('参与活动成功')
      fetchEventDetail() // 重新获取详情，更新参与状态和人数
    } else {
      ElMessage.error(res.msg || '参与活动失败')
    }
  } catch (error) {
    console.error('参与活动异常:', error)
    ElMessage.error('参与活动失败')
  } finally {
    actionLoading.value = false
  }
}

// 取消参与
const handleCancelJoin = async () => {
  try {
    await ElMessageBox.confirm('确定要取消参与该活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    actionLoading.value = true
    const res = await cancelJoinEvent(eventId.value)
    if (res.code === 200) {
      ElMessage.success('已取消参与')
      fetchEventDetail() // 重新获取详情，更新参与状态和人数
    } else {
      ElMessage.error(res.msg || '取消参与失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消参与异常:', error)
      ElMessage.error('取消参与失败')
    }
  } finally {
    actionLoading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 编辑活动
const editEvent = () => {
  router.push(`/event/edit/${eventId.value}`)
}

// 票种更新处理
const handleTicketUpdate = () => {
  // 可以在此处更新活动相关状态
  fetchEventDetail()
}
</script>

<style scoped>
.event-detail-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.event-detail-card {
  background-color: var(--card-background);
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
  padding: 24px;
  min-height: 500px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.event-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-tag {
  font-size: 14px;
  padding: 6px 12px;
}

.detail-info {
  margin-top: 20px;
}

.info-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
}

.label {
  font-weight: 500;
  color: var(--text-secondary);
  min-width: 100px;
}

.value {
  color: var(--text-primary);
  flex: 1;
}

.description-section, .notes-section, .participants-section {
  margin-top: 24px;
}

.description-section h3, .notes-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 16px;
}

.event-description, .event-notes {
  font-size: 15px;
  line-height: 1.6;
  color: var(--text-primary);
  white-space: pre-line;
  background-color: var(--background-color);
  padding: 16px;
  border-radius: var(--radius-small);
  border-left: 4px solid var(--primary-color);
}

.event-notes {
  white-space: pre-line;
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

.tickets-section {
  margin-top: 24px;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.event-cover {
  width: 100%;
  max-width: 800px;
  height: auto;
  max-height: 400px;
  margin: 0 auto;
  display: block;
  border-radius: 8px;
  box-shadow: var(--shadow-light);
}

.cover-section {
  margin: 20px 0;
  text-align: center;
  width: 100%;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 300px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 18px;
}

.error-hint {
  font-size: 12px;
  margin-top: 5px;
  color: #909399;
}

/* 参与者列表 */

.page-header .header-actions .el-button {
  font-weight: 500;
  border-radius: 8px;
  color: var(--text-primary); /* 普通按钮文字颜色 */
}

.page-header .header-actions .el-button--primary {
  color: #ffffff; /* 主要按钮文字颜色 */
}

.image-error .el-button {
  color: #ffffff; /* 图片错误按钮文字颜色 */
}

:deep(.el-button--primary) {
  background: #5e5ce6;
  border-color: #5e5ce6;
  color: #ffffff !important; /* 确保主要按钮文字为白色 */
}

:deep(.el-button--primary:hover) {
  background: #6b69e3;
  border-color: #6b69e3;
  color: #ffffff !important;
}

/* 使得票种管理的添加票种按钮文字可见 */
:deep(.ticket-management .ticket-header .el-button) {
  color: #ffffff !important; /* 确保票种管理头部按钮文字为白色 */
}

/* 对话框中的按钮 */
:deep(.dialog-footer .el-button--primary) {
  color: #ffffff !important; /* 确保对话框中的主要按钮文字为白色 */
}
</style> 